<template>
    <div id="session" style="height: 93vh;" class="flex-1 py-5 sm:px-6 lg:px-5 flex flex-col ml-64">
        <div class="flex-1 bg-white shadow-md rounded-lg p-4 overflow-y-auto" ref="chatArea">
            <!-- 聊天消息区域 -->
            <div class="flex flex-col space-y-4">
                <div v-for="(message, index) in chatMessages" :key="index"
                    :class="{ 'flex justify-start': !message.isUser, 'flex justify-end': message.isUser }">
                    <div :class="{ 'bg-gray-200': !message.isUser, 'bg-blue-100': message.isUser }"
                        class="p-3 rounded-lg max-w-xl">
                        <!--展示消息内容-->
                        <div v-html="processContent(message.content)"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router';
import { useHistoryApi } from '../../../api/history';
import { ElMessage } from 'element-plus';
import MarkdownIt from 'markdown-it';
const route = useRoute();
const md = new MarkdownIt();
const historyApi = new useHistoryApi();

const chatMessages = ref([]);
// 控制全图模态框的显示和隐藏
const chatArea = ref(null)
// 接收路由传递的sessionId
const sessionId = ref(route.query.sessionId);

// 处理内容
const processContent = (content) => {
    let newContent = content.replace(/<ref>\[(\d+)\]<\/ref>/g, '【$1】');
    newContent = md.render(newContent);
    return newContent;
};

// 获取历史对话记录
const fetchHistoryDetail = () => {
    historyApi.getHistoryDetail(sessionId.value).then(response => {
        if (response.data.code == 1) {
            const dataList = response.data.data.dataList;
            for (const index in dataList) {
                chatMessages.value.push({
                    isUser: true,
                    content: dataList[index].content,
                });
                chatMessages.value.push({
                    isUser: false,
                    content: dataList[index].answer,
                });
            }
        } else {
            ElMessage.error(response.data.message);
        }
    }).catch(error => {
        console.error(error);
    })
}

// 监听 sessionId 的变化
watch(() => route.query.sessionId, (newValue) => {
    console.log(newValue);
    sessionId.value = newValue;
    chatMessages.value = [];
    fetchHistoryDetail();
});

onMounted(() => {
    fetchHistoryDetail();
});
</script>

<style scoped></style>